package com.sdkj.fixed.asset.assets.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.sdkj.fixed.asset.api.assets.in_vo.*;
import com.sdkj.fixed.asset.api.assets.out_vo.*;
import com.sdkj.fixed.asset.api.login.out_vo.CompanyBaseListResult;
import com.sdkj.fixed.asset.api.login.pojo.LoginRole;
import com.sdkj.fixed.asset.api.login.pojo.LoginUser;
import com.sdkj.fixed.asset.assets.mapper.*;
import com.sdkj.fixed.asset.assets.util.*;
import com.sdkj.fixed.asset.common.base.BaseMapper;
import com.sdkj.fixed.asset.common.base.BaseService;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.common.utils.JpushClientUtil;
import com.sdkj.fixed.asset.common.utils.TimeTool;
import com.sdkj.fixed.asset.pojo.assets.*;
import com.sdkj.fixed.asset.pojo.system.OrgManagement;
import com.sdkj.fixed.asset.pojo.system.PushManagement;
import com.sdkj.fixed.asset.pojo.system.UserManagement;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Author zhangjinfei
 * @Description //TODO 资产领用
 * @Date 2020/7/21 10:54
 */
@Service
public class CollectService extends BaseService<Collect> {

    private  final Logger log = LoggerFactory.getLogger(CollectService.class);

    @Resource
    private CollectMapper mapper;
    @Resource
    private AssetLogMapper assetLogMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private CacheUtils cacheUtils;
    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private WarehouseHistoryMapper historyMapper;
    @Autowired
    private AssetReceiveMapper assetReceiveMapper;
    @Autowired
    private SetService setService;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private StandModelMapper standModelMapper;
    @Autowired
    private AssetReportService assetReportService;
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private PushManagementMapper pushMapper;



    private final static String TABLE_NAME="as_asset_receive";
    private final static String COLUMN_NAME="receive_id";

    @Override
    public BaseMapper getMapper() {
        return mapper;
    }

    public List<CollectResult> queryPages(PageParams<SearchNameParam> params){

        //--------- 权限 start
        String token = request.getHeader("token");
        // redis 查询用户权限： 如果是管理员为false 查询全部
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        List<LoginRole> loginRoles = loginUser.getLoginRoles();
        List<String> roles = loginRoles.stream().map(LoginRole::getRoleLevel).collect(Collectors.toList());
        List<CompanyBaseListResult> companys = loginUser.getCompanys();
        String orgId = companys.get(0).getCompanyId();
        Integer isAllData = reportMapper.selectUserIsAllDataAuth(userId);
        if(isAllData==1){
            userId = null;
        }
        //--------- 权限 end
        PageHelper.startPage(params.getCurrentPage(),params.getPerPageTotal());
        List<CollectResult> list = mapper.queryPages(params.getParams().getSearchName(), orgId , userId );
        list.stream().forEach(e->{
            String receiveId = e.getReceiveId();
            List<WarehouseHistoryResult> warehouseList = historyMapper.queryWarehouseHistory(receiveId,1);
            e.setWarehouseList(warehouseList);
        });
        return list;
    }

    public Integer insertCollect(CollectParam collect) {

        //--------- 权限 start
        String token = request.getHeader("token");
        // redis 查询用户权限： 如果是管理员为false 查询全部
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        List<LoginRole> loginRoles = loginUser.getLoginRoles();
        List<String> roles = loginRoles.stream().map(LoginRole::getRoleLevel).collect(Collectors.toList());
        List<CompanyBaseListResult> companys = loginUser.getCompanys();
        String orgId = companys.get(0).getCompanyId();
        //--------- 权限 end
        Long increment = redisUtil.getIncr("LY_"+orgId+"_"+DateTools.nowDayStr(),DateTools.expiresTime());
        String no = String.format("%04d",Long.valueOf(increment));
        collect.setReceiveNo("LY"+DateTools.nowDayStr()+no);
        collect.setOrgId(orgId);
        collect.setApproval(2); // 已审批
        collect.setCollectType(0); // 管理员发放
        collect.setState(1); // 未签字
        collect.setCreateTime(DateTools.nowDate());
        collect.setCreateUser(userId);
        collect.setUpdateTime(DateTools.nowDate());
        collect.setUpdateUser(userId);
        collect.setIsDelete(0);
        // 通过领用人修改领用公司和领用部门
        UserManagement user = warehouseMapper.queryUserByUserId(collect.getReceiveUserId());
        OrgManagement org = warehouseMapper.queryOrgById(user.getCompanyId());
        OrgManagement dept = warehouseMapper.queryOrgById(user.getDeptId());
        collect.setReceiveCompany(org.getId());
        collect.setReceiveCompanyTreecode(org.getTreecode());
        collect.setReceiveDept(dept.getId());
        collect.setReceiveDeptTreecode(dept.getTreecode());

        int i = mapper.insertSelective(collect);
        List<String> assetIdList = collect.getAssetIdList();
        for (String assetId:assetIdList) {
            if(!redisUtil.setnx(assetId,1800)){
                throw new LogicException("请核对资产状态是否发生改变");
            }
            Warehouse warehouse = warehouseMapper.selectByPrimaryKey(assetId);
            if("待发放".equals(warehouse.getState())){
                throw new LogicException("请核对资产状态是否发生改变");
            }
            AssetReceive assetReceive = new AssetReceive();
            assetReceive.setReceiveId(collect.getReceiveId());
            assetReceive.setAssetId(assetId);
            assetReceive.setIsDeleted(0);
            assetReceive.setType(1);
            assetReceive.setCreateUser(userId);
            assetReceive.setCreateDate(TimeTool.getCurrentTimeStr());
            assetReceive.setUpdateUser(userId);
            assetReceive.setUpdateDate(TimeTool.getCurrentTimeStr());
            assetReceiveMapper.insertSelective(assetReceive);

        }
        historyMapper.batchInsert(assetIdList ,collect.getReceiveId(),1);
        //修改资产状为领用
        warehouseService.updateAssetState(collect.getAssetIdList(), "待发放",null,null);
        // 添加日志
        insertLog(collect);


        //推送消息给领用人
        String[] asia = {collect.getReceiveUserId()};
        String notification_title = "领用资产发放";
        String msg_title = "领用资产发放";
        String msg_content = "领用资产已发放，单号【"+ collect.getReceiveNo() +"】请签字";
        log.info("领用资产发放,消息推送人："+ JSONObject.toJSONString(asia));
        JpushClientUtil.sendToAsia(asia, notification_title, msg_title, msg_content,"");
        String finalMsg_content = msg_content;
        Arrays.stream(asia).forEach(e->{
            PushManagement pu = new PushManagement();
            pu.setCompanyId(orgId);
            pu.setContent(finalMsg_content);
            pu.setCtime(DateTools.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            pu.setCuser(userId);
            pu.setSender(e);
            pu.setResult(0);
            pushMapper.insertSelective(pu);
        });
        
        collect.getAssetIdList().forEach(
            e->{
                redisUtil.delkey(e);
            }
        );
        return i;
    }


    public Integer updateSign(SignatureParam param) {
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        CollectParam collect = new CollectParam();
        collect.setReceiveId(param.getId());
        collect.setSignPic(param.getSignPic());
        collect.setState(2);
        collect.setUpdateTime(DateTools.nowDate());
        collect.setUpdateUser(userId);
        int i = mapper.updateByPrimaryKeySelective(collect);

        // 修改审批表状态为签字 4
        Collect apply = mapper.selectByPrimaryKey(collect.getReceiveId());
        if(StringUtils.isNotEmpty(apply.getApplyId())){
            AssetReceive arApply = new AssetReceive();
            arApply.setId(apply.getApplyId());
            arApply.setState(4);
            arApply.setUpdateDate(DateTools.nowDate());
            arApply.setUpdateUser(userId);
            assetReceiveMapper.updateByPrimaryKeySelective(arApply);
        }

        CollectResult coll = queryCollect(param.getId());
        Warehouse warehouse = new Warehouse();
        warehouse.setState("在用");


        warehouse.setHandlerUser(coll.getReceiveUser());
        warehouse.setHandlerUserId(coll.getReceiveUserId());
        warehouse.setUseCompany(coll.getReceiveCompany());
        warehouse.setUseCompanyTreecode(coll.getReceiveCompanyTreecode());
        warehouse.setUseDepartment(coll.getReceiveDept());
        warehouse.setUseDeptTreecode(coll.getReceiveDeptTreecode());
        warehouse.setArea(coll.getReceiveArea());
        warehouse.setStorageLocation(coll.getReceiveAddress());
        List<String> assetIdList = coll.getWarehouseList().stream().map(e -> e.getAssetId() ).collect(Collectors.toList());
        warehouseService.updateAsset(assetIdList, warehouse);
        String[] split = coll.getReceiveDate().split("-");
        for (String assetId:assetIdList ) {
            AssetReport assetReport = new AssetReport();
            assetReport.setAssetId(assetId);
            assetReport.setArYear(split[0]);
            assetReport.setArMonth(split[1]);
            assetReport.setArDay(split[2]);
            assetReport.setUseType(1);
            assetReport.setUseUserId(collect.getReceiveUserId());
            assetReportService.insertReport(assetReport);
        }
        insertLog3(assetIdList,param.getId());
        return i;
    }

    // 添加日志
    private void insertLog(CollectParam collect) {
        //--------- 权限 start
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();

        //--------- 权限 end
        List<String> assetIdList = collect.getAssetIdList();
        for (String assetId:assetIdList) {
            AssetLog assetLog = new AssetLog();
            assetLog.setCreateTime(DateTools.nowDate());
            assetLog.setCreateUser(userId);
            assetLog.setUpdateTime(DateTools.nowDate());
            assetLog.setUpdateUser(userId);
            assetLog.setLogType("领用");
            assetLog.setAssetId(assetId);
            assetLog.setHandlerUser(collect.getHandlerUser());
            assetLog.setHandlerId(collect.getReceiveId());

            LogContext context  =  new LogContext();
            context.setModelName("领用");
            context.setBeforeName("<空>");
            context.setAfterName(collect.getReceiveUser());
            context.setBeforeState("闲置");
            context.setAfterState("待发放");
            assetLog.setHandlerContext(ChangLogUtil.simpleLogContxt(context));
            assetLogMapper.insertSelective(assetLog);
        }
    }

    private void insertLog2(List<String> assetIdList) {
        //--------- 权限 start
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();

        for (String assetId:assetIdList) {
            AssetLog assetLog = new AssetLog();
            assetLog.setCreateTime(DateTools.nowDate());
            assetLog.setCreateUser(userId);
            assetLog.setUpdateTime(DateTools.nowDate());
            assetLog.setUpdateUser(userId);
            assetLog.setLogType("领用");
            assetLog.setAssetId(assetId);
            assetLog.setHandlerUser(userName);
            assetLog.setHandlerContext("管理员"+userName+"将修改或删除领用单");
            assetLogMapper.insertSelective(assetLog);
        }
    }
    private void insertLog3(List<String> assetIdList,String id) {
        //--------- 权限 start
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();

        for (String assetId:assetIdList) {
            AssetLog assetLog = new AssetLog();
            assetLog.setCreateTime(DateTools.nowDate());
            assetLog.setCreateUser(userId);
            assetLog.setUpdateTime(DateTools.nowDate());
            assetLog.setUpdateUser(userId);
            assetLog.setLogType("领用");
            assetLog.setAssetId(assetId);
            assetLog.setHandlerId(id);
            assetLog.setHandlerUser(userName);
            assetLog.setHandlerContext("用户["+userName+"]已签字成功");
            assetLogMapper.insertSelective(assetLog);
        }
    }
    /**
     * 修改领用
     * @param collect
     */
    public Integer updateCollect(CollectParam collect) throws Exception {
        String token = request.getHeader("token");
        String orgId = request.getHeader("orgId");
        // redis 查询用户权限： 如果是管理员为false 查询全部
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        collect.setUpdateTime(DateTools.nowDate());
        collect.setUpdateUser(userId);
        int i = mapper.updateByPrimaryKeySelective(collect);

        //删除之前的资产中间表
        Example example = new Example(AssetReceive.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("receiveId", collect.getReceiveId());
        List<AssetReceive> assetReceives = assetReceiveMapper.selectByExample(example);
        assetReceiveMapper.deleteByExample(example);
        List<String> delAssetIdList = assetReceives.stream().map(e -> e.getAssetId()).collect(Collectors.toList());
        // 恢复数据状态
        warehouseService.updateAssetState(delAssetIdList, "闲置",null,null);
        // 删除之前的资产明细
        Example example2 = new Example(WarehouseHistory.class);
        Example.Criteria criteria2 = example2.createCriteria();
        criteria2.andEqualTo("handerId", collect.getReceiveId());
        criteria2.andEqualTo("handerType", 1);
        historyMapper.deleteByExample(example2);
        // 修改日志
        insertLog2(delAssetIdList);

        List<String> assetIdList = collect.getAssetIdList();
        //新增
        for (String assetId:assetIdList) {
            AssetReceive assetReceive = new AssetReceive();
            assetReceive.setReceiveId(collect.getReceiveId());
            assetReceive.setAssetId(assetId);
            assetReceive.setType(1);
            assetReceive.setIsDeleted(0);
            assetReceive.setCreateUser(userId);
            assetReceive.setCreateDate(TimeTool.getCurrentTimeStr());
            assetReceive.setUpdateUser(userId);
            assetReceive.setUpdateDate(TimeTool.getCurrentTimeStr());
            assetReceiveMapper.insertSelective(assetReceive);
        }
        // 添加历史
        historyMapper.batchInsert(assetIdList ,collect.getReceiveId(),1);
        warehouseService.updateAssetState(assetIdList, "待发放",null,null);

        // 添加日志
        insertLog(collect);

        Collect collect1 = mapper.selectByPrimaryKey(collect.getReceiveId());
        //推送消息给领用人
        String[] asia = {collect1.getReceiveUserId()};
        String notification_title = "领用资产发放";
        String msg_title = "领用资产发放";
        String msg_content = "领用资产已发放，单号【"+ collect1.getReceiveNo() +"】请签字";
        log.info("领用资产发放,消息推送人："+ JSONObject.toJSONString(asia));
        JpushClientUtil.sendToAsia(asia, notification_title, msg_title, msg_content,"");

        String finalMsg_content = msg_content;
        Arrays.stream(asia).forEach(e->{
            PushManagement pu = new PushManagement();
            pu.setCompanyId(orgId);
            pu.setContent(finalMsg_content);
            pu.setCtime(DateTools.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            pu.setCuser(userId);
            pu.setSender(e);
            pu.setResult(0);
            pushMapper.insertSelective(pu);
        });

        return i;
    }

    /**
     * 主键ID 查询 结果集
     * @param collectId
     * @return
     */
    public CollectResult queryCollect(String collectId) {
        CollectResult result = mapper.selectByReceiveId(collectId);
        List<WarehouseHistoryResult> warehouseResults = historyMapper.queryWarehouseHistory( collectId,1);
        result.setWarehouseList(warehouseResults);
        return result;
    }

    /**
     * 删除领用
     * @param receiveId
     */
    public Integer deleteCollect(String receiveId) throws Exception {
        //删除关联表
        Example example = new Example(AssetReceive.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("receiveId", receiveId);
        List<AssetReceive> assetReceiveList = assetReceiveMapper.selectByExample(example);
        List<String> assetIdList = assetReceiveList.stream().map(e -> {
            return e.getAssetId();
        }).collect(Collectors.toList());
        assetReceiveMapper.deleteByExample(example);

        // 删除主表
        int i = mapper.deleteByPrimaryKey(receiveId);
        warehouseService.updateAssetState(assetIdList, "闲置",null,null);

        // 删除之前的资产明细
        Example example2 = new Example(WarehouseHistory.class);
        Example.Criteria criteria2 = example2.createCriteria();
        criteria2.andEqualTo("handerId", receiveId);
        criteria2.andEqualTo("handerType", 1);
        historyMapper.deleteByExample(example2);

        // 删除日志
        insertLog2(assetIdList);
        return i ;
    }

    public List<CollectExport> queryAll(String token,String searchName) {
        //--------- 权限 start
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        List<LoginRole> loginRoles = loginUser.getLoginRoles();
        List<String> roles = loginRoles.stream().map(LoginRole::getRoleLevel).collect(Collectors.toList());
        List<CompanyBaseListResult> companys = loginUser.getCompanys();
        String orgId = companys.get(0).getCompanyId();
         Integer isAllData = reportMapper.selectUserIsAllDataAuth(userId);
        if(isAllData==1){
            userId = null;
        }
        //--------- 权限 end
        List<CollectExport> listCollectExport = new ArrayList<>();

        List<CollectResult> list = mapper.queryPages(searchName,orgId,userId);
        list.stream().forEach(e->{
            String receiveId = e.getReceiveId();
            List<WarehouseHistoryResult> warehouseList = historyMapper.queryWarehouseHistory(receiveId,1);
            e.setWarehouseList(warehouseList);
            CollectExport collectExport = new CollectExport();
            BeanUtils.copyProperties(e,collectExport);

            List<WarehouseBase> listBase = new ArrayList<>();
            warehouseList.stream().forEach(w->{
                WarehouseBase base = new WarehouseBase();
                BeanUtils.copyProperties(w,base);
                listBase.add(base);
            });
            collectExport.setList(listBase);
            listCollectExport.add(collectExport);
        });
        return listCollectExport;
    }
    public Workbook printCollect(List<String> collectIdList){
        HSSFWorkbook wb=new HSSFWorkbook();
        String title = "资产领用单";
        for (String collectId:collectIdList) {
//       数据
            CollectResult  collectResult = queryCollect(collectId);
            String sheetName=collectResult.getReceiveNo();
            HSSFSheet sheet=wb.createSheet(sheetName);
            // 设置打印页面
            ExcelStyle.printSetup(sheet);
            sheet.setDefaultColumnWidth(12);
            sheet.setColumnWidth(0,5*256);

            HSSFRow row_title = sheet.createRow(0);
            row_title.setHeight((short) (38 * 20));
            HSSFCell cell_title = row_title.createCell(1);
            cell_title.setCellValue(title);
            cell_title.setCellStyle(ExcelStyle.styleTitle(wb));
            row_title.setHeight((short)690);
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 8)); // 合并单元格显示
            String[] cellName={ "领用单号：","领用日期：","领用人：",
                    "领用后使用公司：","领用后使用部门：","领用后区域：",
                    "领用后存放地点：",
                    "领用备注："};
            String[] cellValue={ collectResult.getReceiveNo(),collectResult.getReceiveDate(),collectResult.getReceiveUser(),
                    collectResult.getReceiveCompanyName(),collectResult.getReceiveDeptName(),collectResult.getReceiveAreaName()};
            AtomicInteger cellCount = new AtomicInteger();
            AtomicInteger valCount = new AtomicInteger();
            for (int i = 1; i < 3 ; i++) {
                HSSFRow row = sheet.createRow(i);
                for(int c = 1 ;c< 9; c++){
                    HSSFCell cell = row.createCell(c);
                    if(c%3==1){
                        cell.setCellValue(cellName[cellCount.getAndIncrement()]);
                        cell.setCellStyle(ExcelStyle.styleNotBorder(wb,0));
                        continue;
                    }
                    if(c%3==0){
                        cell.setCellValue("");
                        cell.setCellStyle(ExcelStyle.styleNotBorder(wb,0));
                        continue;
                    }
                    cell.setCellValue(cellValue[valCount.getAndIncrement()]);
                    cell.setCellStyle(ExcelStyle.styleNotBorder(wb,0));
                }
            }
            // 领用后存放地点
            HSSFRow row = sheet.createRow(3);
            HSSFCell cell = row.createCell(1);
            cell.setCellValue(cellName[6]);
            cell.setCellStyle(ExcelStyle.styleNotBorder(wb,0));

            cell = row.createCell(2);
            cell.setCellValue(collectResult.getReceiveAddress());
            cell.setCellStyle(ExcelStyle.styleNotBorder(wb,0));

            // 领用备注
            row = sheet.createRow(4);
            cell = row.createCell(1);
            cell.setCellValue(cellName[7]);
            cell.setCellStyle(ExcelStyle.styleNotBorder(wb,0));

            cell = row.createCell(2);
            cell.setCellValue(collectResult.getReceiveRemark());
            cell.setCellStyle(ExcelStyle.styleNotBorder(wb,0));
            // 设置边框
            CellRangeAddress cell1 = new CellRangeAddress(1, 1, 2, 3);
            CellRangeAddress cell2 = new CellRangeAddress(2, 2, 2, 3);// 合并单元格显示
            CellRangeAddress cell3 = new CellRangeAddress(3, 3, 2, 8);// 合并单元格显示
            CellRangeAddress cell4 = new CellRangeAddress(4, 4, 2, 8);// 合并单元格显示
            sheet.addMergedRegion(cell1);
            sheet.addMergedRegion(cell2);
            sheet.addMergedRegion(cell3);
            sheet.addMergedRegion(cell4);

            row = sheet.createRow(5);
            row.setHeight((short)600);
            cell = row.createCell(1);
            cell.setCellValue("资产明细：");
            cell.setCellStyle(ExcelStyle.styleNotBorder(wb,1));

            String[] colName={"序号","资产条码","资产类别","资产名称",
                    "规格型号","SN号","金额","管理员"};
            row = sheet.createRow(6);
            AtomicInteger colNum = new AtomicInteger();
            for (int i = 1; i <9; i++) {
                cell = row.createCell(i);
                cell.setCellValue(colName[colNum.getAndIncrement()]);
                cell.setCellStyle(ExcelStyle.styleCellName(wb));
            }
            List<WarehouseHistoryResult> warehouseList = collectResult.getWarehouseList();
            AtomicInteger rowNum = new AtomicInteger(7);
            AtomicInteger numNo = new AtomicInteger(1);
            if(warehouseList!=null) {
                for (int i = 0; i < warehouseList.size(); i++) {
                    WarehouseHistoryResult warehouseResult = warehouseList.get(i);
                    String[] colValue = {warehouseResult.getAssetCode(), warehouseResult.getAssetClassName(),
                            warehouseResult.getAssetName(), warehouseResult.getSpecificationModel(),
                            warehouseResult.getSnNumber(), warehouseResult.getAmount(), warehouseResult.getAdmin()};
                    row = sheet.createRow(rowNum.getAndIncrement());
                    // 序号
                    cell = row.createCell(1);
                    cell.setCellValue(i + 1);
                    cell.setCellStyle(ExcelStyle.styleCellValue(wb));
                    // 数据
                    AtomicInteger cellNum = new AtomicInteger(0);
                    for (int j = 2; j < 9; j++) {
                        cell = row.createCell(j);
                        String str = colValue[cellNum.getAndIncrement()];
                        cell.setCellValue(str);
                        cell.setCellStyle(ExcelStyle.styleCellValue(wb));
                    }
                }
            }
            // 页尾
            row = sheet.createRow(rowNum.getAndIncrement());
            cell = row.createCell(1);
            cell.setCellValue("领用人签字：");
            cell.setCellStyle(ExcelStyle.styleNotBorder(wb,0));

            cell = row.createCell(7);
            cell.setCellValue("签字时间：");
            cell.setCellStyle(ExcelStyle.styleNotBorder(wb,0));
        }
        return wb;
    }

    public Integer insertCollectApply(CollectApplyParam collect) {
        //--------- 权限 start
        String token = request.getHeader("token");
        // redis 查询用户权限： 如果是管理员为false 查询全部
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();
        List<CompanyBaseListResult> companys = loginUser.getCompanys();
        String orgId = companys.get(0).getCompanyId();
        //--------- 权限 end
        Long increment = redisUtil.getIncr("REQ_"+orgId+"_"+DateTools.nowDayStr(),DateTools.expiresTime());
        String no = String.format("%04d",Long.valueOf(increment));
        collect.setReceiveNo("REQ"+DateTools.nowDayStr()+no);

        collect.setApproval(1); // 待审批
        collect.setCollectType(1); // 员工申请
        collect.setState(1); // 未签字

        UserManagement userManagement = warehouseMapper.queryUserByUserId(userId);
        collect.setReceiveUserId(userId);
        String companyId = userManagement.getCompanyId();
        collect.setReceiveCompany(companyId);
        String deptId = userManagement.getDeptId();
        collect.setReceiveDept(deptId);
        String companyTreeCode = userManagement.getCompanyTreeCode();
        collect.setReceiveCompanyTreecode(companyTreeCode);
        String deptTreeCode = userManagement.getDeptTreeCode();
        collect.setReceiveDeptTreecode(deptTreeCode);
        collect.setReceiveDate(DateTools.nowDay());
        collect.setOrgId(orgId);
        collect.setCreateTime(DateTools.nowDate());
        collect.setCreateUser(userId);
        collect.setUpdateTime(DateTools.nowDate());
        collect.setUpdateUser(userId);
        collect.setIsDelete(0);

        Set<String> adminIds =  new HashSet<>();
        int i = mapper.insertSelective(collect);
        for (AssetReceive assetReceive:collect.getAssetReceiveList()) {
            assetReceive.setReceiveId(collect.getReceiveId());
            assetReceive.setIsDeleted(0);
            assetReceive.setCreateUser(userId);
            assetReceive.setCreateDate(TimeTool.getCurrentTimeStr());
            assetReceive.setUpdateUser(userId);
            assetReceive.setUpdateDate(TimeTool.getCurrentTimeStr());
            assetReceive.setState(1);
            assetReceiveMapper.insertSelective(assetReceive);
            //给指定分类或资产管理员推送消息
//            if(assetReceive.getType() == 1){
            //获取资产信息
//                WarehouseResult info = warehouseService.queryByAssetId(assetReceive.getAssetId());
//                String[] asia = {info.getAdmin()};
//                String notification_title = "领用申请";
//                String msg_title = "领用申请";
//                String msg_content = "资产编号：" + info.getAssetCode() +" 领用申请";
//                log.info("领用申请,消息推送人："+ JSONObject.toJSONString(asia));
//                JpushClientUtil.sendToAsia(asia, notification_title, msg_title, msg_content,"");
//            }
//            if(assetReceive.getType() == 2){
            //通过资产标准类型获取资产分类管理人员
//                String[] asia = setService.getUserIdByModelId(Arrays.asList(assetReceive.getAssetId().split(",")));
//                StandModelEntity entity = setService.selStandModelById(assetReceive.getAssetId());
//                if(entity!=null){
//                String notification_title = "领用申请";
//                String msg_title = "领用申请";
//                String msg_content = "资产标准型号：" + entity.getModel() + ",数量：" + assetReceive.getAssetNum() +" 领用申请";
//                log.info("领用申请,消息推送人："+ JSONObject.toJSONString(asia));
//                JpushClientUtil.sendToAsia(asia, notification_title, msg_title, msg_content,"");
//                }
//            }
                List<String> adminIdList = mapper.getModelOrAssetAdmin(orgId, assetReceive.getAssetId(), assetReceive.getType());
                if(!CollectionUtils.isEmpty(adminIdList)){
                    adminIds.addAll(adminIdList);
                }
        }
        String[] asia = adminIds.toArray(new String[adminIds.size()]);
        String notification_title = "领用资产申请";
        String msg_title = "领用资产申请";
        String msg_content = "领用资产申请，单号【"+ collect.getReceiveNo() +"】";
        log.info("领用资产申请,消息推送人："+ JSONObject.toJSONString(asia));
        JpushClientUtil.sendToAsia(asia, notification_title, msg_title, msg_content,"");

        String finalMsg_content = msg_content;
        Arrays.stream(asia).forEach(e->{
            PushManagement pu = new PushManagement();
            pu.setCompanyId(orgId);
            pu.setContent(finalMsg_content);
            pu.setCtime(DateTools.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            pu.setCuser(userId);
            pu.setSender(e);
            pu.setResult(0);
            pushMapper.insertSelective(pu);
        });
        return i;
    }

    public Integer collectApplyAgree(CollectApplyAgreeParam param) {
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String orgId = cacheUtils.getUserCompanyId(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();

        AssetReceive ar =  new AssetReceive();
        ar.setId(param.getId());
        ar.setState(2);
        ar.setUpdateDate(DateTools.nowDate());
        ar.setUpdateUser(userId);
        assetReceiveMapper.updateByPrimaryKeySelective(ar);
        AssetReceive assetReceive = assetReceiveMapper.selectByPrimaryKey(ar);
//        String receiveId = param.getReceiveId();

        // 修改总单状态   同意  2
//        updateApply(receiveId,2);

        UserManagement userManagement = warehouseMapper.queryUserByUsername(userName,orgId,null);
        String id = userManagement.getId();
        param.setUseUserId(id);
        String companyId = userManagement.getCompanyId();
        param.setCompanyId(companyId);
        String deptId = userManagement.getDeptId();
        param.setDeptId(deptId);
        String companyTreeCode = userManagement.getCompanyTreeCode();
        param.setCompanyTreecode(companyTreeCode);
        String deptTreeCode = userManagement.getDeptTreeCode();
        param.setDeptTreecode(deptTreeCode);

        CollectParam collect = new CollectParam();
        collect.setReceiveUserId(assetReceive.getCreateUser());
        collect.setReceiveUser(param.getUseUserName());

        collect.setReceiveCompany(param.getCompanyId());
        collect.setReceiveCompanyTreecode(param.getCompanyTreecode());
        collect.setReceiveDept(param.getDeptId());
        collect.setReceiveDeptTreecode(param.getDeptTreecode());

        collect.setHandlerUser(userName);
        collect.setReceiveDate(DateTools.nowDay());
        collect.setAssetIdList(param.getAssetIdList());
        collect.setApplyId(param.getId());
        //管理员发放
        Integer i = insertCollect(collect);
        return i;
    }

//    private void updateApply(String receiveId,Integer state) {
//        Example example = new Example(AssetReceive.class);
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("receiveId",receiveId);
//        criteria.andEqualTo("state",1);
//        List<AssetReceive> assetReceives = assetReceiveMapper.selectByExample(example);
//        if(assetReceives!=null && assetReceives.size()>0){
//            return;
//        }
//        Collect collect = mapper.selectByPrimaryKey(receiveId);
//
//        String token = request.getHeader("token");
//        LoginUser loginUser = cacheUtils.getUser(token);
//        String userId = loginUser.getUserId();
//
//        Collect collectApply = new Collect();
//        if(collect.getState()!=2){
//            collectApply.setApproval(state);
//        }
//        collectApply.setReceiveId(receiveId);
//        collectApply.setUpdateTime(DateTools.nowDate());
//        collectApply.setUpdateUser(userId);
//        mapper.updateByPrimaryKeySelective(collectApply);
//    }

    public Integer collectApplyRefuse(CollectApplyAgreeParam collect) {
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();

//        AssetReceive ar =  assetReceiveMapper.selectByPrimaryKey(collect.getId());
        AssetReceive ar = new AssetReceive();
        ar.setId(collect.getId());
        ar.setState(3);
        ar.setUpdateDate(DateTools.nowDate());
        ar.setUpdateUser(userId);
        int i = assetReceiveMapper.updateByPrimaryKeySelective(ar);
//        驳回为 3
//        updateApply(collect.getReceiveId(),3);
        return i;
    }
    /**
     * 审批查询
     * @param params
     * @retu
     */
    public List<CollectApplyResult> getAllCollectApply(ApplySelParam params){
        String token = request.getHeader("token");
        String userId = cacheUtils.getUserId(token);
        String date = params.getSelTimeType();
        if("1".equals(date)){
            date = getTime(-1);
        } else if("2".equals(date))  {
            date = getTime(-3);
        } else if("3".equals(date))  {
            date = getTime(-6);
        } else {
            throw new LogicException("查询时间不正确");
        }
        Integer state = params.getState();

        List<CollectApplyResult> list = mapper.getAllCollectApply(date, userId,state);

        if(list != null && list.size()>0){
            for (CollectApplyResult apply : list) {
                //申请明细
                List<AssetReceiveApply> applyAssetList = new ArrayList<>();
                //发放明细
                List<CollectResult> collectResultList = new ArrayList<>();

                // 查询子单符合状态的数据
                Example example = new Example(AssetReceive.class);
                Example.Criteria criteria = example.createCriteria();
//                审批状态
                criteria.andEqualTo("state", state);
                criteria.andEqualTo("receiveId", apply.getReceiveId());
                List<AssetReceive> assetReceiveList = assetReceiveMapper.selectByExample(example);
                if(assetReceiveList != null && assetReceiveList.size() > 0){
                    for (AssetReceive assetReceive : assetReceiveList) {
                        AssetReceiveApply assetReceiveApply = new AssetReceiveApply();
                        BeanUtils.copyProperties(assetReceive,assetReceiveApply);
                        if(assetReceive.getType() == 1){ // 固资
                            Warehouse warehouse = warehouseMapper.selectByPrimaryKey(assetReceive.getAssetId());
                            assetReceiveApply.setAssetCode(warehouse.getAssetCode());
                            assetReceiveApply.setAssetName(warehouse.getAssetName());
                            assetReceiveApply.setUnitMeasurement(warehouse.getUnitMeasurement());
                        } else if(assetReceive.getType() == 2){ // 型号
                            StandModel model = standModelMapper.selectByPrimaryKey(assetReceive.getAssetId());
                            assetReceiveApply.setAssetName(model.getName());
                            assetReceiveApply.setAssetModel(model.getModel());
                            assetReceiveApply.setUnitMeasurement(model.getType());
                        }
                        applyAssetList.add(assetReceiveApply);

                        //申请已审批发放明细
                        if(assetReceive.getState() == 2){ // 已审批 未签字
                            Example example2 = new Example(Collect.class);
                            Example.Criteria criteria2 = example2.createCriteria();
                            criteria2.andEqualTo("applyId", assetReceive.getId());
                            criteria2.andEqualTo("state", 1);
                            Collect collect = mapper.selectOneByExample(example2);
                            if(collect!=null){
                                CollectResult result = queryCollect(collect.getReceiveId());
                                collectResultList.add(result);
                            }
                        }
                        if(assetReceive.getState() == 4){ // 已签字
                            Example example2 = new Example(Collect.class);
                            Example.Criteria criteria2 = example2.createCriteria();
                            criteria2.andEqualTo("applyId", assetReceive.getId());
                            criteria2.andEqualTo("state", 2);
                            Collect collect = mapper.selectOneByExample(example2);
                            if(collect!=null){
                                CollectResult result = queryCollect(collect.getReceiveId());
                                collectResultList.add(result);
                            }
                        }
                    }
                }
                // 申请
                apply.setAssetReceiveList(applyAssetList);
                // 发放
                apply.setCollectResultList(collectResultList);
            }
        }
        return list;
    }

    /**
     * 获取几月之前的时间
     * @param num
     * @return
     */
    private String getTime(int num){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, num);
        Date m = c.getTime();
        return format.format(m);
    }

//    签字后查看详情
    public CollectApplyResult  getCollectApplyById(String id,Integer state){
        String token = request.getHeader("token");
        String userId = cacheUtils.getUserId(token);

//   如果是2  就是已审批待签字   4 就是已审批已签字
//        Integer state = 4;

        CollectApplyResult apply = mapper.getCollectApplyById(id,state);

        //申请明细
        List<AssetReceiveApply> applyAssetList = new ArrayList<>();
        //发放明细
        List<CollectResult> collectResultList = new ArrayList<>();

        // 查询子单符合状态的数据
        Example example = new Example(AssetReceive.class);
        Example.Criteria criteria = example.createCriteria();
//      审批状态
        criteria.andEqualTo("state", state);
        criteria.andEqualTo("receiveId", apply.getReceiveId());
        List<AssetReceive> assetReceiveList = assetReceiveMapper.selectByExample(example);
        if(assetReceiveList != null && assetReceiveList.size() > 0){
            for (AssetReceive assetReceive : assetReceiveList) {
                AssetReceiveApply assetReceiveApply = new AssetReceiveApply();
                BeanUtils.copyProperties(assetReceive,assetReceiveApply);
                if(assetReceive.getType() == 1){
                    Warehouse warehouse = warehouseMapper.selectByPrimaryKey(assetReceive.getAssetId());
                    assetReceiveApply.setAssetCode(warehouse.getAssetCode());
                    assetReceiveApply.setAssetName(warehouse.getAssetName());
                    assetReceiveApply.setUnitMeasurement(warehouse.getUnitMeasurement());
                    assetReceiveApply.setType(1);
                } else if(assetReceive.getType() == 2){
                    StandModel model = standModelMapper.selectByPrimaryKey(assetReceive.getAssetId());
                    assetReceiveApply.setAssetName(model.getName());
                    assetReceiveApply.setAssetModel(model.getModel());
                    assetReceiveApply.setUnitMeasurement(model.getType() == null ? "": model.getType());
                    assetReceiveApply.setAssetNum(assetReceive.getAssetNum());
                    assetReceiveApply.setType(2);
                }
                applyAssetList.add(assetReceiveApply);

                //申请已审批发放明细
                if(assetReceive.getState() == 2){ // 已审批
                    Example example2 = new Example(Collect.class);
                    Example.Criteria criteria2 = example2.createCriteria();
                    criteria2.andEqualTo("applyId", assetReceive.getId());
                    Collect collect = mapper.selectOneByExample(example2);
                    if(collect!=null){
                        CollectResult result = queryCollect(collect.getReceiveId());
                        collectResultList.add(result);
                    }
                }
                if(assetReceive.getState() == 4){ // 已签字
                    Example example2 = new Example(Collect.class);
                    Example.Criteria criteria2 = example2.createCriteria();
                    criteria2.andEqualTo("applyId", assetReceive.getId());
                    criteria2.andEqualTo("state", 2);
                    Collect collect = mapper.selectOneByExample(example2);
                    if(collect!=null){
                        CollectResult result = queryCollect(collect.getReceiveId());
                        collectResultList.add(result);
                    }
                }
            }
        }
        // 申请
        apply.setAssetReceiveList(applyAssetList);
        // 发放
        apply.setCollectResultList(collectResultList);
        return apply;
    }
}
